package com.mvc4g.example.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.mvc4g.client.Controller;
import com.mvc4g.client.Event;
import com.mvc4g.client.ViewInterface;

public class CalculatorView extends Composite implements ViewInterface,
		Constants {

	private static String DIGIT = "digit";
	private static String OPERATION = "operation";

	private Controller controller = null;
	private TextBox screen = new TextBox();

	public CalculatorView() {

		screen.setEnabled(false);
		screen.setWidth("100px");

		Grid buttons = new Grid(5, 3);
		Button button = null;
		int row = 0;
		int col = 0;
		for (int i = 0; i < 10; i++) {
			button = new Button(Integer.toString(i));
			button.addClickHandler(new CalculatorDigitClickHandler(i));
			buttons.setWidget(row, col, button);
			col++;
			if (col > 2) {
				col = 0;
				row++;
			}
		}

		Button add = new Button(ADD);
		add.addClickHandler(new CalculatorOperationClickHandler(ADD));
		buttons.setWidget(4, 0, add);

		Button less = new Button(LESS);
		less.addClickHandler(new CalculatorOperationClickHandler(LESS));
		buttons.setWidget(4, 1, less);

		VerticalPanel mainPanel = new VerticalPanel();

		mainPanel.add(screen);
		mainPanel.add(buttons);

		RootPanel.get().add(mainPanel);
	}

	@Override
	public void setController(Controller controller) {
		this.controller = controller;
	}

	public void setScreen(String value) {
		screen.setText(value);
	}

	class CalculatorDigitClickHandler implements ClickHandler {

		private Event event = null;

		public CalculatorDigitClickHandler(int value) {
			event = new Event(DIGIT, Integer.valueOf(value));
		}

		@Override
		public void onClick(ClickEvent event) {
			controller.handleEvent(this.event);
		}

	}

	class CalculatorOperationClickHandler implements ClickHandler {

		private Event event = null;

		public CalculatorOperationClickHandler(String value) {
			event = new Event(OPERATION, value);
		}

		@Override
		public void onClick(ClickEvent event) {
			controller.handleEvent(this.event);
		}

	}

}
